-- ActivityDungeonsRender

local ClassRef = app.mvc.createRenderClass(...)

local string_split = string.split

local NUM_STR = L("lua_code_text_468")
local BALANCE_STR = L("lua_code_text_218")
local POWER_STR = L("lua_code_text_402")

--data = "teamTarget_first" conf
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.NewNodeTypeNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)

    self._cdTime = 0 -- 开启倒计时

    self:setContentSize(self._ui.Panel:getContentSize())

    self._ui.Panel_dungeons:setVisible(false)
    self._ui.Panel_match:setVisible(false)
    self._ui.Panel_activity:setVisible( true )

    display.uiAddClick(self._ui.Panel, function(sender, eventType)
        executeFunc(self._onOperate, "activityDungeonsRender_selectedTarget", self)
    end, true, 0.02)

    self._markBg = self._ui["Panel/Panel_mark/bg"]
    self._markText = self._ui["Panel/Panel_mark/num"]
    self._tltText = self._ui["Panel/Panel_activity/tlt"]
    self._descText = self._ui["Panel/Panel_activity/text"]
    self._restTimesBg = self._ui["Panel/Panel_activity/bg"] -- 剩余次数底图
    self._restTimes = self._ui["Panel/Panel_activity/num"] -- 剩余次数
    self._cdTimes = self._ui["Panel/Panel_time/tlt_0"] -- cd倒计时

    self._ui.first:setVisible(false)

    self:refresh()
end

-- data = teamTarget_first
function ClassRef:refresh()
    if self._data then
        local data = self._data

        self._markText:setString(string.format(NUM_STR, data.showNum))
        self._tltText:setString(L(data.name))
        self._descText:setString(L(data.desc))
        self:setIcon(Res.teamtarget_pic .. data.banner .. ".png")

        self:_handleWithOpenTime()
    end
end

-- bg底图
function ClassRef:setIcon(res)
    self._ui.img:loadTexture(res)
end

-- 剩余次数
function ClassRef:setRestTimes( restTiems )
    restTiems = restTiems or 0
    if 0 < restTiems then -- 存在剩余次数
        self._restTimesBg:setVisible( true )
        self._restTimes:setVisible( true )
        self._restTimes:setString( string.format( L("left_times"), restTiems ) )
    else
        self._restTimesBg:setVisible( false )
        self._restTimes:setVisible( false )
    end
end

-- 活动开放时间的处理
function ClassRef:_handleWithOpenTime()
    local thirdTargetCfgs = GD:queryTeamThirdTargetByType( self._data.ID )
    assert( 1 == #thirdTargetCfgs, " ------------>>>> _handleWithOpenTime teamTarget_first对应了teamTarget_third个数错误" )
    -- dump( thirdTargetCfgs, " ------------>>>> _handleWithOpenTime " .. self._data.ID )

    -- 距离刷新的时间
    local thirdTargetCfg = thirdTargetCfgs[1]
    local refreshGap = 0
    local isOpen = false -- 开放状态，默认false
    local refreshType = tonumber( thirdTargetCfg.refreshType )
    if refreshType and 0 ~= refreshType then -- 存在开放限制
        local curTime = math.floor(app.session:getServerTime() or app:getTime())
        local curDate = os.date("*t", curTime)

        local minStart = 2^53 -- 最早的开放时间
        local startList = {}
        local endList = {}
        local maxEnd = 0 -- 最晚的结束时间

        if 1 == refreshType then -- 天刷新
            local timeStr  = string.split( thirdTargetCfg.openTime, ";" ) -- { 10-12, 14-18 }
            for i,v in ipairs( timeStr ) do
                -- v = 10-12
                local timeSlot = string.split( v, "-" )

                local realWday = curDate.wday -- 实际的周几
                local startTimeStamp = TimeUtil.getTargetTimeStamp( realWday, unpack( string_split( timeSlot[1], ":" ) ) )
                minStart = math.min( minStart, startTimeStamp )
                table.insert( startList, startTimeStamp )

                local endTimeStamp = TimeUtil.getTargetTimeStamp( realWday, unpack( string_split( timeSlot[2], ":" ) ) )
                maxEnd = math.max( maxEnd, endTimeStamp )
                table.insert( endList, endTimeStamp )
            end
        elseif 2 == refreshType then -- 周刷新
            local timeStr  = string.split( thirdTargetCfg.openTime, ";" ) -- { 6|0-24, 7|0-24 }
            for i,v in ipairs( timeStr ) do
                -- print( " ----------->>>>> " .. i .. " ; " .. v )

                -- v = 6|0-24
                local timeList = string.split( v, "|" ) -- { 6, 0-24 }
                local timeSlot = string.split( timeList[2], "-" ) -- { 0, 24 }

                local confWday = tonumber( timeList[1] ) -- 配置的周几
                local realWday = 0 -- 实际的周几
                if  7 == confWday then
                    realWday = 1
                else
                    realWday = confWday + 1
                end

                local startTimeStamp = TimeUtil.getTargetTimeStamp( realWday, unpack( string_split( timeSlot[1], ":" ) ) )
                minStart = math.min( minStart, startTimeStamp )
                table.insert( startList, startTimeStamp )

                local endTimeStamp = TimeUtil.getTargetTimeStamp( realWday, unpack( string_split( timeSlot[2], ":" ) ) )
                maxEnd = math.max( maxEnd, endTimeStamp )
                table.insert( endList, endTimeStamp )
            end
        end

        -- print( " ----------->>>>>A " .. os.date( minStart ) .. " ; " .. os.date( maxEnd ) )
        -- print( " ----------->>>>>B " .. os.date( curTime ) )
        if curTime < minStart then -- 全部未开始
            refreshGap = minStart - curTime
        elseif curTime > maxEnd then -- 全部结束
            if 1 == refreshType then -- 天刷新
                refreshGap = ( minStart + 24*60*60 ) - curTime
            elseif 2 == refreshType then -- 周刷新
                refreshGap = ( minStart + 7*24*60*60 ) - curTime
            end
        else
            for i = 1, #startList do
                if startList[i] <= curTime and curTime <= endList[i] then -- 处在某一个开放周期内
                    isOpen = true
                    refreshGap = endList[i] - curTime
                    break
                end
            end
            if not isOpen then -- 没开放？
                local offsetStart = 2^53 -- 距离最近的开放时间差
                for i = 1, #startList do
                    local offset = startList[i] - curTime
                    if 0 < offset then -- 后面待开放的时间差值
                        offsetStart = math.min( offsetStart, offset )
                    end
                end
                refreshGap = offsetStart
            end
        end
    end
    if isOpen then -- 已经开放？
        self:_setTimeCDPanelShown( false )
    else
        if 0 < refreshGap then
            self:_setTimeCDPanelShown( true )
            self:_setCDTime( refreshGap )
        else
            self:_setTimeCDPanelShown( false )
        end
    end
end

-- cd时间panel显示与否
function ClassRef:_setTimeCDPanelShown( isVisible )
    isVisible = isVisible or false
    self._ui.Panel_time:setVisible( isVisible )
end
-- 设置cd时间
function ClassRef:_setCDTime( timeSecond ) -- cd倒计时
    self._cdTime = timeSecond or 0
    self:_setCDTimeStr()
    if 0 < self._cdTime then
        if self.tickNumId then
            self:stopAction(self.tickNumId)
            self.tickNumId = nil
        end
        self.tickNumId = self:schedule(function()
            self._cdTime = self._cdTime - 1
            if 0 >= self._cdTime then
                self:_handleWithOpenTime()
            end
            self:_setCDTimeStr()
        end,1)
    end
end
function ClassRef:_setCDTimeStr()
    if 0 >= self._cdTime then
        return
    end

    local day, time = TimeUtil.secondsToStr( self._cdTime , 1 )
    local offlineStr = ""
    if 0 < day then
        offlineStr = string.format(L("lua_code_text_374"), day)
    end
    offlineStr = offlineStr .. time .. "\n"

    -- self._cdTimes:setString( string.format( table.concat( { offlineStr, "\n", L("后开启") } ) ) )
    self._cdTimes:setString(string.format(L("lua_code_text_154"), offlineStr))
end


function ClassRef:setClickEnable(b)
    self._ui.Panel:setTouchEnabled(b)
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

return ClassRef
